package com.eslserver.dao;

import java.math.BigInteger;
import java.sql.SQLException;
import java.util.Collection;

import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eslserver.to.Group;
import com.eslserver.to.wrapper.ESLCollectionPageWrapper;
import com.eslserver.util.HibernateUtil;

public class DBGroupDAO implements GroupDAO {

	public static final Logger LOG = LoggerFactory.getLogger(DBGroupDAO.class);

	protected DBGroupDAO() throws SQLException {
		// Empty protected constructor to avoid unnecessary initialization
	}

	@Override
	public Group addGroup(Group group) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.save(group);
		return group;
	}

	@Override
	public void updateGroup(Group group) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.update(group);
	}

	@Override
	public Group loadGroup(Integer groupID) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Group group = (Group) session.load(Group.class, groupID);
		return group;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Group> loadAllGroups() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Group group = Group.createGroup();
		group.setDelete(false);

		Example example = Example.create(group);

		Collection<Group> groupCollection = session.createCriteria(Group.class)
				.add(example).list();

		return groupCollection;
	}

	@Override
	public void deleteGroup(Integer groupID) {
		Group group = loadGroup(groupID);
		if (group != null) {
			group.setDelete(true);
			updateGroup(group);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public ESLCollectionPageWrapper<Group> loadGroupByPageQuery(String sQuery,
			String aQuery) {
		ESLCollectionPageWrapper<Group> groupCollectionPageWrapper = new ESLCollectionPageWrapper<Group>();

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Collection<Group> groupCollection = session.createSQLQuery(sQuery)
				.addEntity(Group.class).list();

		String foundQuery = aQuery;
		BigInteger foundCount = (BigInteger) session.createSQLQuery(foundQuery)
				.uniqueResult();
		groupCollectionPageWrapper.setFilteredTotal(foundCount.intValue());

		String allQuery = "SELECT COUNT(*) FROM esl_group WHERE isDelete=false";
		BigInteger allCount = (BigInteger) session.createSQLQuery(allQuery)
				.uniqueResult();
		groupCollectionPageWrapper.setTotal(allCount.intValue());

		groupCollectionPageWrapper.getESLCollection().addAll(groupCollection);

		return groupCollectionPageWrapper;
	}

}
